/*
 * Copyright 2011 Powersi. All rights reserved.
 */
package com.powersi.sys.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import com.powersi.hygeia.web.util.JsonHelper;
import com.powersi.hygeia.web.util.WebHelper;

/**
 * The Class DataGridHelper.
 */
public abstract class DataGridHelper {
	/**
	 * Render.
	 * 
	 * @param response
	 *            the response
	 * @param data
	 *            the data
	 */
	public static void render(HttpServletResponse response, Object data) {
		if (response == null) {
			return;
		}

		Map<String, Object> map = new HashMap<String, Object>();

		if (data == null) {

		} else if (data instanceof DBPaginatedList) {
			DBPaginatedList paginatedList = (DBPaginatedList) data;

			if (paginatedList.getFullListSize() > 0) {
				int total = (int) Math.ceil((double) paginatedList
						.getFullListSize() / paginatedList.getObjectsPerPage());
				if (total < 1) {
					total = 1;
				}

				map = new HashMap<String, Object>();

				map.put("page", paginatedList.getPageNumber());
				map.put("total", total);
				map.put("records", paginatedList.getFullListSize());
				map.put("rows", paginatedList.getList());
			}

		} else if (data instanceof Collection) {
			Collection coll = (Collection) data;
			if (coll.size() > 0) {
				map = new HashMap<String, Object>();

				map.put("page", 1);
				map.put("total", 1);
				map.put("records", coll.size());
				map.put("rows", coll);
			}
		} else {
			List lst = new ArrayList();
			lst.add(data);
			map = new HashMap<String, Object>();

			map.put("page", 1);
			map.put("total", 1);
			map.put("records", 1);
			map.put("rows", lst);
		}

		if (map.size() == 0) {
			map.put("page", 1);
			map.put("total", 0);
			map.put("records", 0);
			map.put("rows", Collections.EMPTY_LIST);
		}

		WebHelper.writeText(response, JsonHelper.toJson(map));
	}
}
